#!/bin/bash
# MySQL5.7安装脚本

# 检查MySQL是否已安装
if sudo rpm -q mysql-community-server > /dev/null 2>&1; then
    echo "MySQL is already installed."
    exit 0
fi

#关闭防火墙
systemctl stop firewalld

# 检查MySQL 5.7的Yum仓库配置文件是否存在
if ! rpm -q mysql57-community-release-el7-11.noarch > /dev/null 2>&1; then
    # 如果不存在则下载并安装
    wget https://dev.mysql.com/get/mysql57-community-release-el7-11.noarch.rpm
    sudo rpm -Uvh mysql57-community-release-el7-11.noarch.rpm
fi

# 安装MySQL 5.7
sudo yum install --nogpgcheck mysql-community-server-5.7.44-1.el7.x86_64

# 启动MySQL服务
sudo systemctl start mysqld

# 设置开机自启
sudo systemctl enable mysqld

# 获取MySQL初始随机密码
MYSQL_INIT_PASSWORD=$(grep 'temporary password' /var/log/mysqld.log | awk '{print $NF}')

# 登录MySQL并更改root密码
echo "ALTER USER 'root'@'localhost' IDENTIFIED BY '1qaz@WSX';" | sudo mysql -u root --connect-expired-password -p"${MYSQL_INIT_PASSWORD}"

echo "GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '1qaz@WSX'; FLUSH PRIVILEGES;" | sudo mysql -u root -p"1qaz@WSX"


# 清除客户端历史记录，防止密码泄露
history -c

echo "MySQL 5.7 has been installed and secured. Root password is set to 【1qaz@WSX】"